package com.joysuch.wwyt.attendance.service.impl;

import com.joysuch.wwyt.attendance.bean.AttendanceApiUserBean;
import com.joysuch.wwyt.attendance.bo.AttendanceApiBatchUserBo;
import com.joysuch.wwyt.attendance.mapper.AttendanceUserMapper;
import com.joysuch.wwyt.attendance.service.AttendanceApiUserService;
import com.joysuch.wwyt.bp.entity.bean.TaskForAssignBean;
import com.joysuch.wwyt.core.common.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author ZhaoQiuWei
 * @Date 2022/3/12 17:40
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class AttendanceApiUserServiceImpl implements AttendanceApiUserService {

    @Autowired
    private AttendanceUserMapper userMapper;

    @Override
    public List<Long> userTaskCheck(Date startDate, List<Long> userIds) {
        List<Long> returnIds = new ArrayList<>();
//        try {
//            if (startDate == null && CollectionUtils.isEmpty(userIds)) {
//                return returnIds;
//            }
//            List<Long> yesterdayIds = new ArrayList<>();
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(startDate);
//            int year = calendar.get(Calendar.YEAR);
//            int month = calendar.get(Calendar.MONTH) + 1;
//            int day = calendar.get(Calendar.DATE);
//            int hour = calendar.get(Calendar.HOUR_OF_DAY);
//            int minute = calendar.get(Calendar.MINUTE);
//            convertApiUserTask(returnIds, userIds, yesterdayIds, year, month, day, hour, minute, null);
//            //跨天需要多查一天
//            if (!CollectionUtils.isEmpty(yesterdayIds)) {
//                calendar.add(Calendar.DATE, -1);
//                int y = calendar.get(Calendar.YEAR);
//                int m = calendar.get(Calendar.MONTH) + 1;
//                int d = calendar.get(Calendar.DATE);
//                convertApiUserTask(returnIds, yesterdayIds, new ArrayList<>(), y, m, d, hour, minute, 1);
//            }
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//        }
        return returnIds;
    }

    @Override
    public List<TaskForAssignBean> batchUserTaskCheck(List<TaskForAssignBean> beanList) {
        if (CollectionUtils.isEmpty(beanList)) {
            return beanList;
        }
        List<Integer> yearList = new ArrayList<>();
        List<Integer> monthList = new ArrayList<>();
        List<Integer> dayList = new ArrayList<>();
        List<Long> userList = new ArrayList<>();
        for (TaskForAssignBean bean : beanList) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(bean.getStartTime());
            AttendanceApiUserBean nowBean = new AttendanceApiUserBean(calendar);
            calendar.add(Calendar.DATE, -1);
            AttendanceApiUserBean oldBean = new AttendanceApiUserBean(calendar);
            if (!yearList.contains(nowBean.getYear())) {
                yearList.add(nowBean.getYear());
            }
            if (!yearList.contains(oldBean.getYear())) {
                yearList.add(oldBean.getYear());
            }
            if (!monthList.contains(nowBean.getMonth())) {
                monthList.add(nowBean.getMonth());
            }
            if (!monthList.contains(oldBean.getMonth())) {
                monthList.add(oldBean.getMonth());
            }
            if (!dayList.contains(nowBean.getDay())) {
                dayList.add(nowBean.getDay());
            }
            if (!dayList.contains(oldBean.getDay())) {
                dayList.add(oldBean.getDay());
            }
            userList.addAll(bean.getAssignList());
        }
        userList = userList.stream().distinct().collect(Collectors.toList());
        List<AttendanceApiBatchUserBo> userDataList = userMapper.selectApiBatchUser(userList, yearList, monthList, dayList);
        if (CollectionUtils.isEmpty(userDataList)) {
            return beanList;
        }
        return convertApiBatchUserTask(beanList, userDataList);
    }

    private List<TaskForAssignBean> convertApiBatchUserTask(List<TaskForAssignBean> beanList, List<AttendanceApiBatchUserBo> userDataList) {
        List<TaskForAssignBean> dataList = new ArrayList<>();
        Map<Long, List<AttendanceApiBatchUserBo>> map = userDataList.stream().collect(Collectors.groupingBy(AttendanceApiBatchUserBo::getUserId));
        //遍历入参集合
        for (TaskForAssignBean bean : beanList) {
            TaskForAssignBean data = new TaskForAssignBean();
            data.setTaskId(bean.getTaskId());
            data.setStartTime(bean.getStartTime());
            List<Long> userIds = new ArrayList<>();
            List<Long> assignList = bean.getAssignList();
            List<AttendanceApiBatchUserBo> boList = new ArrayList<>();
            //遍历入参人员集合 校验人员信息
            for (Long uId : assignList) {
                boList = map.get(uId);
                if (!CollectionUtils.isEmpty(boList)) {
                    for (AttendanceApiBatchUserBo bo : boList) {
                        //校验日期
                        if (this.checkData(bo, bean.getStartTime())) {
                            if (!userIds.contains(uId)) {
                                userIds.add(uId);
                            }
                        }
                    }
                }
            }
            if (CollectionUtils.isEmpty(userIds)) {
                //如果当前无人有班次,则算上所有人员
                userIds = bean.getAssignList();
            }
            data.setAssignList(userIds);
            dataList.add(data);
        }
        return dataList;
    }


//    /**
//     * @param returnIds    在班次时段内的id集合
//     * @param importIds    需做判断的人员id集合
//     * @param failedIds    不在时间段内的id集合
//     * @param year
//     * @param day
//     * @param hour
//     * @param minute
//     * @param crossdayFlag 0不跨天 1跨天
//     * @return
//     */
//    private void convertApiUserTask(List<Long> returnIds, List<Long> importIds, List<Long> failedIds, Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer crossdayFlag) {
//        List<AttendanceApiUserBo> userList = userMapper.selectApiUsers(importIds, year, month, day, crossdayFlag);
//        if (!CollectionUtils.isEmpty(userList)) {
//            Map<Long, List<AttendanceApiUserBo>> userMap = userList.stream().collect(Collectors.groupingBy(AttendanceApiUserBo::getUserId));
//            for (Long uId : importIds) {
//                boolean flag = false;
//                List<AttendanceApiUserBo> dtos = userMap.get(uId);
//                if (!CollectionUtils.isEmpty(dtos)) {
//                    for (AttendanceApiUserBo dto : dtos) {
//                        if (checkData(dto.getStartTime(), dto.getEndTime(), hour, minute, dto.getCrossdayFlag())) {
//                            flag = true;
//                            if (!returnIds.contains(uId)) {
//                                returnIds.add(uId);
//                            }
//                        }
//                    }
//                }
//                if (!flag && !failedIds.contains(uId)) {
//                    failedIds.add(uId);
//                }
//            }
//        } else {
//            failedIds.addAll(importIds);
//        }
//    }

    //    private boolean checkData(String startTime, String endTime, Integer hour, Integer minute, Integer croFlag) {
//        LocalTime sTime = DateTimeUtil.String2LocalTime(startTime, "HH:mm");
//        LocalTime eTime = DateTimeUtil.String2LocalTime(endTime, "HH:mm");
//        String hourStr = hour.toString() + ":";
//        String minStr = minute.toString();
//        if (hour < 10) {
//            hourStr = "0" + hour + ":";
//        }
//        if (minute < 10) {
//            minStr = "0" + minute;
//        }
//        LocalTime time = DateTimeUtil.String2LocalTime(hourStr + minStr, "HH:mm");
//        if (croFlag.intValue() == 0) {
//            if ((time.isAfter(sTime) && time.isBefore(eTime)) || time.equals(sTime)) {
//                return true;
//            }
//        } else if (croFlag.intValue() == 1) {
//            if ((time.isBefore(sTime) && time.isBefore(eTime)) || time.equals(sTime)) {
//                return true;
//            }
//        }
//        return false;
//    }
    private boolean checkData(AttendanceApiBatchUserBo bo, Date taskTime) {
        String month = bo.getAttendanceMonth() < 10 ? "0" + bo.getAttendanceMonth() : bo.getAttendanceMonth().toString();
        String day = bo.getAttendanceDay() < 10 ? "0" + bo.getAttendanceDay() : bo.getAttendanceDay().toString();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime tTime = DateTimeUtil.dateToLocalDateTime(taskTime);
        LocalDateTime sTime = LocalDateTime.parse(bo.getAttendanceYear() + "-" + month + "-" + day + " " + bo.getStartTime() + ":00", dtf);
        LocalDateTime eTime = LocalDateTime.parse(bo.getAttendanceYear() + "-" + month + "-" + day + " " + bo.getEndTime() + ":00", dtf);
        //跨天结束时间加1天计算
        if (bo.getCrossdayFlag().intValue() == 1) {
            LocalDateTime eDateTime = sTime.plusDays(1);
            String m = eDateTime.getMonthValue() < 10 ? "0" + eDateTime.getMonthValue() : String.valueOf(eDateTime.getMonthValue());
            String d = eDateTime.getDayOfMonth() < 10 ? "0" + eDateTime.getDayOfMonth() : String.valueOf(eDateTime.getDayOfMonth());
            eTime = LocalDateTime.parse(eDateTime.getYear() + "-" + m + "-" + d + " " + bo.getEndTime() + ":00", dtf);
        }
        if (!tTime.isBefore(sTime) && tTime.isBefore(eTime)) {
            return true;
        }
        return false;
    }


    private String getKey(Long userId, Integer year, Integer month, Integer day) {
        return userId + "_" + year + "_" + month + "_" + day;
    }
}
